package com.example.demo.config;


import com.example.demo.entity.ResultEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 数据校验
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResultEntity handBindException(BindException exception){
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode(-1);
        StringBuilder errorMsg = new StringBuilder();
        exception.getAllErrors().forEach(ele -> {
            System.out.println(ele.getDefaultMessage());
            errorMsg.append(ele.getDefaultMessage()).append(",");
        });
        resultEntity.setMessage(errorMsg.toString());
        return resultEntity;
    }

}
